<template>
  <div class="unloadImg flex">
    <div class="imgs">
      <div v-for="(i, index) in imageListUrl"
           :key="index"
           class="forbox">
        <el-image v-if="i.fileType == 'image'"
                  :src="i.url"
                  :preview-src-list="previewList"
                  :initial-index="previewIndex"
                  :preview-teleported="true"
                  @click="previewIndex = index"
                  alt="加载失败" />
        <video controls
               class="videoBox"
               :src="i.url"
               v-if="i.fileType == 'video'"></video>
        <el-icon class="close"
                 @click="deleteImg(index)"
                 color="red">
          <CloseBold />
        </el-icon>
      </div>
    </div>
    <el-upload v-if="imageListUrl.length - 0 < showNum"
               accept="image/*"
               :http-request="unloadUrl">
      <el-icon>
        <Plus />
      </el-icon>
    </el-upload>
  </div>
</template>

<script>
/* 新建一个 cos.js，导出 cos 实例 */
import { ElMessage } from "element-plus";
import COS from "cos-js-sdk-v5"; // 通过 npm 安装的 SDK
const cos = new COS({
  SecretId: "AKIDY2oZHrHV7LYmsqhS8gGnDZfB7v9A51Qk",
  SecretKey: "KYhsz33xnR2CE6nYEmAZagdT6c3LVVYa",
});

export default {
  props: {
    uploadImgList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    showNum: {
      type: Number,
      default: () => {
        return null;
      },
    },
    disabled: {
      type: Number,
      default: () => {
        return null;
      },
    },
  },
  mounted () {
    let _this = this;
    setTimeout(() => {
      if (_this.uploadImgList.length - 0 > 0) {
        _this.imageListUrl = this.uploadImgList;
        _this.previewList = this.uploadImgList.map(a => a.url)
      }
    }, 500);
  },
  data () {
    return {
      previewIndex: null,
      imageListUrl: [],
      previewList: [],
    };
  },
  methods: {
    deleteImg (i) {
      this.imageListUrl.splice(i, 1);
      this.previewList.splice(i, 1);
      this.$emit("changeUploadImgList", this.imageListUrl);
    },
    unloadUrl (file) {
      if (file.file.size > 1024 * 1024 * 20) {
        ElMessage({
          message: "视频图片大小超过20M,请压缩后上传",
          type: "error",
        });
        return;
      }
      const defBase = import.meta.env
      cos.uploadFile(
        {
          Bucket: defBase.VITE_bucket /* 填写自己的 bucket，必须字段 */,
          Region: "ap-chengdu" /* 存储桶所在地域，必须字段 */,
          Key: 'PT/' + Date.now().toString() /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: file.file, // 上传文件对象
          SliceSize:
            1024 *
            1024 *
            5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
          onProgress: function (progressData) {
            // console.log(JSON.stringify(progressData));上传文件数据
          },
        },
        (err, data) => {
          if (err) {
            console.log("上传失败", err);
          } else {
            console.log("上传成功", data);
            this.imageListUrl.push({
              url: "https://" + data.Location,
              fileType: file.file.type.substring(
                0,
                file.file.type.indexOf("/")
              ),
            });
            let fileType = file.file.type.substring(
              0,
              file.file.type.indexOf("/")
            );
            if (fileType == "image") {
              this.previewList.push("https://" + data.Location);
            }
          }
        }
      );
      this.$emit("changeUploadImgList", this.imageListUrl);
    },
  },
};
</script>

<style lang="scss" scoped>
.videoBox {
  height: 100px;
  width: auto;
  margin-right: 10px;
}
.forbox {
  position: relative;
  .close {
    cursor: pointer;
    position: absolute;
    right: 15px;
    top: 5px;
  }
}
::v-deep(.el-dialog__header) {
  border: none;
}
::v-deep(.el-upload-list__item) {
  width: 100px;
  height: 100px;
}
.imgs {
  display: flex;
  height: 100px;
}
::v-deep(.el-image) {
  height: 100px;
  margin-right: 10px;
  width: 100px;
  cursor: pointer;
  background-color: rgba(255, 255, 255, 1);
  border: 1px #ccc dashed;
}
::v-deep(.el-upload-list__item) {
  display: none;
}
::v-deep(.el-upload) {
  width: 100px;
  height: 100px;
  border-radius: 2px;
  text-align: center;
  line-height: 100px;
  font-size: 26px;
  cursor: pointer;
  background-color: rgba(255, 255, 255, 1);
  border: 1px #ccc dashed;
}
</style>
